package dao

import (
	"fmt"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/bindlogs"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

// -------------------- dao层 - 绑定日志相关操作 -----------------------//

type BindLogsDao struct {
}

func NewBindLogsDao() *BindLogsDao {
	return &BindLogsDao{}
}

// InsertBindLogs            新增登录日志
func (d *BindLogsDao) InsertBindLogs(m *bindlogs.BindLogsModel) *dingo.ErrorWrap {

	db := global.Orm.Table("bind_logs").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

// GetBindLogsList 微信绑定日志
func (d *BindLogsDao) GetBindLogsList(param *request.WxBindLogsListReq) *dingo.ErrorWrap {
	var (
		lst    []bindlogs.BindLogsList
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)
	db := global.Orm.Table("bind_logs l").
		Select("l.*", "u.phone as user_phone,u.name,u.user_name as u_name").
		Joins("LEFT JOIN users u ON l.user_id = u.id")
	if param.UserName != "" { db.Where("u.user_name like ?", fmt.Sprint("%", param.UserName, "%")) }
	if param.Name != "" { db.Where("u.name like ?", fmt.Sprint("%", param.Name, "%")) }
	if param.LoginIp != "" { db.Where("l.login_ip = ?", param.LoginIp) }
	if param.Phone != "" { db.Where("l.phone = ?", param.Phone) }
	if param.UserPhone != "" { db.Where("u.phone = ?", param.UserPhone) }
	db.Order("l.id desc")
	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}
